import { IPageTab } from '@/typings'
import { computed, defineComponent, ref, Teleport, TransitionGroup, watch } from 'vue'
import { CloseOutlined } from '@ant-design/icons-vue'
import { RouterLink, useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import './style.less'

export default defineComponent({
  name: 'ScrollTabs',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore()

    const pageTabs = computed<Array<IPageTab>>(() => store.state.common.pageTabs)
    const setRouter = (payload: IPageTab) => store.dispatch('common/setRouter', payload)
    const delRouter = (path: string) => store.dispatch('common/delRouter', path)
    const isActive = (key: string) => route.path === key
    const menuPop = ref<boolean>(false)

    const openMenuTools = (key: string) => {
      console.log(123)
      menuPop.value = true
    }

    const closeMenus = () => { menuPop.value = false }

    watch(menuPop, (val) => {
      if (val) {
        document.body.addEventListener('click', closeMenus)
      } else {
        document.body.removeEventListener('click', closeMenus)
      }
    })

    watch(() => route.path, (val) => {
      if (val !== '/home') {
        const title = route.meta?.title
        setRouter({ key: route.path, title })
      }
    }, { immediate: true })

    return () => {
      return (
        <div class="scroll-tabs-wrapper">
          <RouterLink to="/home" class={['tabs-item', isActive('/home') && 'active']}>首页</RouterLink>
          <TransitionGroup name="rubberBand">
            {
              pageTabs.value.map((item: IPageTab) => (
                <a
                  key={item.key}
                  onContextmenu={(e) => { e.stopPropagation(); openMenuTools(item.key) } }
                  onClick={(e) => { e.stopPropagation(); router.push(item.key) } }
                  class={['tabs-item', isActive(item.key) && 'active']}
                >
                  { item.title }
                  <span class="close" onClick={(e) => { e.stopPropagation(); delRouter(item.key) }}><CloseOutlined /></span>
                </a>
              ))
            }
          </TransitionGroup>
          <Teleport to="body">
            <div class="tab-menus-wrapper" v-show={menuPop.value}>
              <span>删除</span>
              <span>删除全部</span>
            </div>
          </Teleport>
        </div>
      )
    }
  }
})
